import json
import configparser
import sys

KEY_COOKIES = ["SESSDATA", "bili_jct", "DedeUserID", "DedeUserID__ckMd5", "buvid3"]

def read_json_from_stdin():
    print("请粘贴 cookie JSON 文本，输入空行后回车结束：")
    lines = []
    while True:
        line = sys.stdin.readline()
        if not line.strip():
            break
        lines.append(line)
    raw_json = '\n'.join(lines)  # 保证换行结构
    return raw_json


def extract_cookies_from_json_string(json_string):
    data = json.loads(json_string)
    if isinstance(data, dict):
        cookies = data.get("cookies", [])
    elif isinstance(data, list):
        cookies = data
    else:
        cookies = []

    result = {}
    for c in cookies:
        if not isinstance(c, dict):
            continue
        name = c.get("name")
        value = c.get("value")
        if name in KEY_COOKIES and value:
            result[name] = value
    return result


def save_cookies_to_ini(cookies_dict, ini_path='config.ini'):
    config = configparser.ConfigParser(interpolation=None)
    config.read(ini_path, encoding='utf-8')
    if not config.has_section('cookies'):
        config.add_section('cookies')
    for k, v in cookies_dict.items():
        config.set('cookies', k, v)
    with open(ini_path, 'w', encoding='utf-8') as f:
        config.write(f)
    print(f"✅ 成功写入 {len(cookies_dict)} 个 Cookie 到 {ini_path}")
    print("内容如下：")
    for k, v in cookies_dict.items():
        print(f"{k} = {v}")

if __name__ == "__main__":
    try:
        json_string = read_json_from_stdin()
        cookies_dict = extract_cookies_from_json_string(json_string)
        if not cookies_dict:
            print("❌ 没有找到目标 Cookie，请确认 JSON 格式正确且包含目标字段。")
        else:
            save_cookies_to_ini(cookies_dict)
    except json.JSONDecodeError as e:
        print(f"❌ JSON 解析错误：{e}")
